//
//  OJModel.m
//  openJira
//
//  Created by Vincent Demay on 01/05/10.
//  Copyright 2010 Goojet. All rights reserved.
//

#import "OJXMLRPCModel.h"
#import "OJConnector.h"
#import "UserData.h"


@implementation OJXMLRPCModel


////////////// XMLRPCConnectionDelegate //////////////
- (void)request: (XMLRPCRequest *)request didReceiveResponse: (XMLRPCResponse *)response {
	NSLog((NSString*)[response body]);
	if ([response isFault]) {
		
		//see if the response is fault because of invalid token
		//FIXME : found out a better way to know that token becames invalid
		NSRange textRange = [[response faultString] rangeOfString:@"RemoteAuthenticationException"];
		if(textRange.location != NSNotFound) {
			//try to login again in order to get a new token
			NSString *login = [UserData sharedData].login;
			NSString *password = [UserData sharedData].password;
			if ([[OJConnector getDefault] loginWithUser:login andPassword:password]) {
				//login sucessfull
				//send again the request
				NSMutableArray *parameters = [[NSMutableArray alloc] init];
				for (int i=0; i<[[request parameters] count]; i++) {
					if (i == 0) {
						//token position
						[parameters addObject:[OJConnector getDefault].token];
					} else {
						[parameters addObject:[[request parameters] objectAtIndex:i]];
					}
				}
				[request setMethod:[request method] withParameters:parameters];
				XMLRPCConnectionManager *manager = [XMLRPCConnectionManager sharedManager];
				[manager spawnConnectionWithXMLRPCRequest:request delegate:self];
				return;
			}
		}
		
		//else just say to inherited "an error occur"
		[self request:request onResponseError:response];
	} else {
		[self request:request onResponseSuccessfull:response];
	}
}

- (void)request: (XMLRPCRequest *)request didFailWithError: (NSError *)error {
	//[delegate object:self isReady:YES];
}

- (void)request: (XMLRPCRequest *)request didReceiveAuthenticationChallenge: (NSURLAuthenticationChallenge *)challenge {
}

- (void)request: (XMLRPCRequest *)request didCancelAuthenticationChallenge: (NSURLAuthenticationChallenge *)challenge {
}

// This method should be extended to handle response from the server
- (void) request:(XMLRPCRequest *)request onResponseSuccessfull:(XMLRPCResponse*) response{}
- (void) request:(XMLRPCRequest *)request onResponseError:(XMLRPCResponse*) response{}



@end
